package com.shxc.smarttrade.old.presenter;

import android.os.Handler;
import android.util.Log;

import com.shxc.smarttrade.old.bean.RealTimeQuoteDatas;
import com.shxc.smarttrade.old.iview.IViewRealTimeQuote;
import com.shxc.smarttrade.old.modal.IRequestServiceListener;
import com.shxc.smarttrade.old.modal.ObtainRealTimeQuote;
import com.shxc.smarttrade.old.utils.Logger;

import java.util.List;

/**
 * Created by jcdev1 on 2017/5/22.
 */

public class MainPresenter {
    private IViewRealTimeQuote iViewRealTimeQuote;
    private ObtainRealTimeQuote obtainRealTimeQuote;
    private Handler handler = new Handler();
    private Runnable runnable;

    public MainPresenter(IViewRealTimeQuote iViewRealTimeQuote) {
        this.iViewRealTimeQuote = iViewRealTimeQuote;
        this.obtainRealTimeQuote = new ObtainRealTimeQuote();
    }

    /**
     * 请求实时报价
     *
     * @param symbol
     */
    private void getRealTimeQuotoDatas(String symbol) {

        obtainRealTimeQuote.getRealTimeQuoteDatas(symbol, new IRequestServiceListener() {
            @Override
            public void success(Object result) {
                final List<RealTimeQuoteDatas.DataBean.QuoteBean> quoteBeen = (List<RealTimeQuoteDatas.DataBean.QuoteBean>) result;
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        iViewRealTimeQuote.setData(quoteBeen);
                    }
                });
            }

            @Override
            public void faild(String msg) {
                Log.e("MainPresenter", msg);
//                handler.post(new Runnable() {
//                    @Override
//                    public void run() {
//                        iViewRealTimeQuote.showDialog();
//                    }
//                });
            }
        });
    }

    public void startRealTimeQuote(final String symbol) {
        Logger.e("symbol:::", symbol + "");
        stopRealTimerQuote();
        runnable = new Runnable() {
            @Override
            public void run() {
                getRealTimeQuotoDatas(symbol);
                handler.postDelayed(this, 1000);
            }
        };
        handler.post(runnable);
    }

    public void stopRealTimerQuote() {
        if (runnable != null && handler != null)
            handler.removeCallbacks(runnable);
    }
}
